<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/2/20
 * Time: 16:46
 */

namespace app\admin\controller;


use think\Db;

class Member extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $where = [
                'user_status' => ['neq', 3],
                'user_verify' => 2,
                'user_type' => 1,
            ];
//            if(isset($uid) && $uid != ''){
//                $where['user_id'] = $uid;
//            }
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_hospital|user_room'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($province) && $province != "")
            {
                $where['user_sheng'] = $province;
            }
            if(isset($city) && $city != "")
            {
                $where['user_shi'] = $city;
            }
            if(isset($user_sex) && $user_sex != "")
            {
                $where['user_sex'] = $user_sex;
            }
            if(isset($user_status) && $user_status != "")
            {
                $where['user_status'] = $user_status;
            }
            //注册时间查询
            if(isset($start) && $start != "" && isset($end) && $end == "")
            {
                $where['user_time'] = ['>=',$start];
            }
            if(isset($end) && $end != "" && isset($start) && $start == "")
            {
                $where['user_time'] = ['<=',$end];
            }
            if(isset($start) && $start != "" && isset($end) && $end != "")
            {
                $where['user_time'] = ['between',[$start,$end]];
            }
            //登录时间查询
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend == "")
            {
                $where['user_logintime'] = ['>=',$loginstart];
            }
            if(isset($loginend) && $loginend != "" && isset($loginstart) && $loginstart == "")
            {
                $where['user_logintime'] = ['<=',$loginend];
            }
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend != "")
            {
                $where['user_logintime'] = ['between',[$loginstart,$loginend]];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('u_user')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('u_user')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('user_time desc')
                ->select();
            foreach ($lists as $key => $vo){
//                省市
                $area = [$vo['user_sheng'],$vo['user_shi']];
                $ss = Db::table('up_area')
                    ->where('district_id','in',$area)
                    ->column('district');
                $lists[$key]['areastr'] = implode($ss,'-');
//                科室-职位
                $lists[$key]['room_job'] = $vo['user_room'].'-'.$vo['user_job_desc'];
//                sae数和项目数
                $lists[$key]['saenum'] = Db::table('up_sae')
                    ->where('sae_send_uid',$vo['user_id'])
                    ->count();
                $lists[$key]['pronum'] = Db::table('up_project_user')
                    ->where('pu_user_id',$vo['user_id'])
                    ->where('pu_status',2)
                    ->count();
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $school = Db::table('up_u_user')
            ->field('user_hospital')
            ->group('user_hospital')
            ->select();
        $province = Db::table('up_area')
            ->field('district_id,district')
            ->where('pid',0)
            ->select();
        $this->assign([
            'school' => $school,
            'province' => $province,
        ]);
        return $this->fetch();
    }
    
    /**
     * 冻结
     * @return \think\response\Json
     */
    public function down(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 2);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 启用
     * @return \think\response\Json
     */
    public function up(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 1);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function del(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 3);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 详情
     * @return mixed
     */
    public function memberDetail(){
        $user_id = input('user_id');
        $info = Db::name('u_user')
            ->where('user_id', $user_id)
            ->find();
        //                省市
        $area = [$info['user_sheng'],$info['user_shi']];
        $ss = Db::table('up_area')
            ->where('district_id','in',$area)
            ->column('district');
        $info['areastr'] = implode($ss,'-');
//                sae数和项目数
        $info['saenum'] = Db::table('up_sae')
            ->where('sae_send_uid',$info['user_id'])
            ->count();
        $info['pronum'] = Db::table('up_project_user')
            ->where('pu_user_id',$info['user_id'])
            ->where('pu_status',2)
            ->count();
        $this->assign('info', $info);
        return $this->fetch('member/memberdetail');
    }
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelin(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $today = date('Y-m-d H:i:s');
            $data = [];
            for ($i=2;$i<=$highestRow;$i++) {
                $phone = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//手机号
                $name = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue ();//手机号
                if($phone != ''){
                    if(preg_match("/^1[123456789]\d{9}$/", $phone)){
                        $have = Db::table('up_u_user')
                            ->where('user_phone', $phone)
                            ->field('user_id')
                            ->find();
                        if($have){
                            return json(['code' => 100, 'msg' => '手机号已存在！']);
                        }else{
                            $token = md5(date('YmdHis') . rand(10000,99999) . $i);
                            $insert = array();
                            $insert['user_password'] = md5($phone);
                            $insert['user_time'] = $today;
                            $insert['user_updatetime'] = $today;
                            $insert['user_logintime'] = $today;
                            $insert['user_token'] = $token;
                            $insert['user_phone'] = $phone;
                            $insert['user_username'] = $name;
                            $ram = Db::table('up_about')->where('id',6)->value('content');
                            $insert['user_ram'] = (int)$ram * 1024;
                            $data[] = $insert;
                        }
                    }else{
                        return json(['code' => 100,'msg'=>"此手机号（{$phone}）错误"]);
                    }
                }
            }
            if($data){
                $res = Db::table('up_u_user')->insertAll($data);
                if($res){
                    return json(['code' => 200,'msg'=>"导入成功"]);
                }else{
                    return json(['code' => 100,'msg'=>"导入失败"]);
                }
            }else{
                return json(['code' => 100,'msg'=>"有效数据为空"]);
            }
        }
        return $this->fetch();
    }
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function outExcel(){
        extract(input());
        set_time_limit(0);//防止超时
        $where = [
            'user_status' => ['neq', 3],
            'user_verify' => 2,
            'user_type' => 1,
        ];
//            if(isset($uid) && $uid != ''){
//                $where['user_id'] = $uid;
//            }
        if(isset($keyword) && $keyword != ''){
            $where['user_id|user_phone|user_username|user_hospital|user_room'] = ['like', '%' . $keyword . '%'];
        }
        if(isset($province) && $province != "")
        {
            $where['user_sheng'] = $province;
        }
        if(isset($city) && $city != "")
        {
            $where['user_shi'] = $city;
        }
        if(isset($user_sex) && $user_sex != "")
        {
            $where['user_sex'] = $user_sex;
        }
        if(isset($user_status) && $user_status != "")
        {
            $where['user_status'] = $user_status;
        }
        //注册时间查询
        if(isset($start) && $start != "" && isset($end) && $end == "")
        {
            $where['user_time'] = ['>=',$start];
        }
        if(isset($end) && $end != "" && isset($start) && $start == "")
        {
            $where['user_time'] = ['<=',$end];
        }
        if(isset($start) && $start != "" && isset($end) && $end != "")
        {
            $where['user_time'] = ['between',[$start,$end]];
        }
        //登录时间查询
        if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend == "")
        {
            $where['user_logintime'] = ['>=',$loginstart];
        }
        if(isset($loginend) && $loginend != "" && isset($loginstart) && $loginstart == "")
        {
            $where['user_logintime'] = ['<=',$loginend];
        }
        if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend != "")
        {
            $where['user_logintime'] = ['between',[$loginstart,$loginend]];
        }
        if($ids){
            if($ids != 'all'){
                $where['user_id'] = ['in',$ids];
            }
        }else{
            return json(['code'=>0,'msg'=>'请选择数据！']);
        }
        $field = [
            'user_id','user_username','user_phone','user_sex', 'concat(a1.district,"-",a2.district) ss',
            'user_hospital','concat(user_room,"-",user_job_desc) room_job','user_id saenum','user_id pronum','user_status',
            'user_time','user_logintime'
        ];
        $data = Db::table('up_u_user u')
            ->join('up_area a1','u.user_sheng = a1.district_id','left')
            ->join('up_area a2','u.user_shi = a2.district_id','left')
            ->where($where)
            ->order('user_status asc,user_time desc')
            ->field($field)
            ->select();
        if($data){
            foreach ($data as $key => $vo){
//                sae数和项目数
                $data[$key]['saenum'] = Db::table('up_sae')
                    ->where('sae_send_uid',$vo['user_id'])
                    ->count();
                $data[$key]['pronum'] = Db::table('up_project_user')
                    ->where('pu_user_id',$vo['user_id'])
                    ->where('pu_status',2)
                    ->count();
            }
            $cellname = [
                '用户ID', '姓名', '手机号', '性别', '医院所在省市',
                '所在医院', '科室-职称', '上报SAE数', '项目数', '状态',
                '注册时间', '最近登录时间'
            ];
            $status = ['user_sex','user_status'];
            $values = [
                'user_sex' => [1 => '男',2 => '女'],
                'user_status' => [1 => '正常',2 => '冻结']
            ];
            $res = exportExcel('userdata',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}